<template>
  <div>
    <n-grid class="mt-4" cols="1 s:1 m:1 l:3 xl:3 2xl:3" responsive="screen" :x-gap="12">
      <n-gi span="1">
        <n-card :segmented="{ content: true }" :bordered="false" size="small">
          <template #header>
            <n-space>
              <n-button type="info" @click="openCreateDrawer">
                添加菜单
                <template #icon>
                  <n-icon>
                    <FileAddOutlined />
                  </n-icon>
                </template>
              </n-button>
              <n-button type="info" ghost icon-placement="left" @click="packHandle">
                全部{{ expandedKeys.length ? '收起' : '展开' }}
                <template #icon>
                  <div class="flex items-center">
                    <n-icon size="14">
                      <AlignLeftOutlined />
                    </n-icon>
                  </div>
                </template>
              </n-button>
            </n-space>
          </template>
          <div class="w-full menu">
            <n-input type="input" v-model:value="pattern" placeholder="输入菜单名称搜索">
              <template #suffix>
                <n-icon size="18" class="cursor-pointer">
                  <SearchOutlined />
                </n-icon>
              </template>
            </n-input>
            <div class="py-3 menu-list">
              <template v-if="loading">
                <div class="flex items-center justify-center py-4">
                  <n-spin size="medium" />
                </div>
              </template>
              <template v-else>
                <n-tree
                  block-line
                  cascade
                  :virtual-scroll="true"
                  :pattern="pattern"
                  :data="treeData"
                  :expandedKeys="expandedKeys"
                  style="max-height: 650px; overflow: hidden"
                  @update:selected-keys="selectedTree"
                  @update:expanded-keys="onExpandedKeys"
                />
              </template>
            </div>
          </div>
        </n-card>
      </n-gi>
      <n-gi span="2">
        <n-card :segmented="{ content: true }" :bordered="false" size="small">
          <template #header>
            <n-space>
              <n-icon size="18">
                <FormOutlined />
              </n-icon>
              <span>编辑菜单{{ treeItemTitle ? `：${treeItemTitle}` : '' }}</span>
            </n-space>
          </template>
          <MenuForm
            ref="menuFormRef"
            v-if="isEditMenu"
            :form="formParams"
            :treeData="treeData"
            :addFlag="false"
            :submitOk="reloadTree"
          />
        </n-card>
      </n-gi>
    </n-grid>
    <n-drawer v-model:show="isDrawer" width="650" placement="right">
      <n-drawer-content title="添加菜单" closable>
        <MenuForm
          ref="menuFormRef"
          :form="formParams"
          :addFlag="true"
          :treeData="treeData"
          :submitOk="reloadTree"
        />
        <template #footer>
          <n-space>
            <n-button type="primary" :loading="drawerLoading" @click="drawerSubmit">提交</n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>
<script lang="ts" setup>
  import { ref, unref, reactive, onMounted } from 'vue';
  import { FileAddOutlined, AlignLeftOutlined, SearchOutlined, FormOutlined } from '@vicons/antd';
  import { getAllPermission } from '@/api/system/permission';
  import { getTreeItem } from '@/utils';
  import MenuForm from './menuForm.vue';

  const menuFormRef = ref();

  let treeItemKey = ref([]);

  let expandedKeys = ref([]);

  const treeData = ref([]);

  const loading = ref(true);
  const isEditMenu = ref(false);
  const isDrawer = ref(false);
  const treeItemTitle = ref('');
  const pattern = ref('');

  const formParams = reactive({
    id: undefined,
    parentKey: '',
    parentId: '',
    type: 1,
    name: '',
    title: '',
    icon: '',
    path: '',
    redirect: '',
    component: '',
    sort: 1,
    keepAlive: '',
  });

  function openCreateDrawer() {
    isEditMenu.value = false;
    isDrawer.value = true;
    resetForm();
  }

  function selectedTree(keys) {
    if (keys.length) {
      const treeItem = getTreeItem(unref(treeData), keys[0]);
      treeItemKey.value = keys;
      treeItemTitle.value = treeItem.label;
      Object.assign(formParams, treeItem);
      isEditMenu.value = true;
    } else {
      isEditMenu.value = false;
      treeItemKey.value = [];
      treeItemTitle.value = '';
    }
  }

  function onExpandedKeys(keys) {
    expandedKeys.value = keys;
  }

  function packHandle() {
    if (expandedKeys.value.length) {
      expandedKeys.value = [];
    } else {
      expandedKeys.value = unref(treeData).map((item: any) => item.key as string) as [];
    }
  }

  const drawerLoading = ref(false);
  function drawerSubmit() {
    drawerLoading.value = true;
    const { formSubmit } = menuFormRef.value;
    formSubmit();
    drawerLoading.value = false;
  }

  async function loadPermission() {
    console.log('loadPermission');
    loading.value = true;
    const permissions = await getAllPermission();
    treeData.value = getTreePermissions(permissions);
    loading.value = false;
  }

  onMounted(async () => {
    loadPermission();
  });

  function reloadTree() {
    if (drawerLoading.value) {
      drawerLoading.value = false;
    }
    isEditMenu.value = false;
    treeItemTitle.value = '';
    loadPermission();
  }

  function resetForm() {
    formParams.id = undefined;
    formParams.parentKey = '';
    formParams.parentId = '';
    formParams.type = 1;
    formParams.name = '';
    formParams.title = '';
    formParams.icon = '';
    formParams.path = '';
    formParams.redirect = '';
    formParams.component = '';
    formParams.sort = 1;
    formParams.keepAlive = '';
  }

  function getTreePermissions(permissions) {
    return permissions.map((item) => {
      const children = item.children ? getTreePermissions(item.children) : [];
      return {
        ...item,
        key: item.name,
        label: item.title,
        children: children,
        isLeaf: children.length == 0,
        parentKey: item.parentName,
      };
    });
  }
</script>
